package com.yh.redisTest.dao.impl;

import com.yh.redisTest.common.RedisDistributionLock;
import com.yh.redisTest.common.RedisLock;
import com.yh.redisTest.dao.UserDao;
import com.yh.redisTest.domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * Created by eason on 2017/4/26.
 */
public class UserDaoImpl  implements UserDao{

    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate ;

    private Log logger =LogFactory.getLog(UserDaoImpl.class);
    @Override
    public void saveUser(final User user) {
        redisTemplate.execute(new RedisCallback<Object>() {

            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(redisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
                        redisTemplate.getStringSerializer().serialize(user.getName()));
                return null;
            }
        });
    }

    @Override
    public User getUser(final long id) {
        return redisTemplate.execute(new RedisCallback<User>() {
            @Override
            public User doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key = redisTemplate.getStringSerializer().serialize("user.uid." + id);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);
                    String name = redisTemplate.getStringSerializer().deserialize(value);
                    User user = new User();
                    user.setName(name);
                    user.setId(id);
                    return user;
                }
                return null;
            }
        });
    }
    @Override
    public void testLock() {
        RedisDistributionLock lock = new RedisDistributionLock(redisTemplate);
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        logger.info(Thread.currentThread().getName()+"欢迎来到,任务争夺战");
        Long locktime =0L; //加锁时间
        String  name =Thread.currentThread().getName();
        try{
            locktime = lock.lock("lockTest", name);
        if (locktime != null) {
            //开始执行任务
            //需要加锁的代码
            logger.info("恭喜"+ Thread.currentThread().getName()+" 5杀");
            //logger.info("__________________________睡觉");
           Thread.sleep(200000);
            logger.info(Thread.currentThread()+"：获得用户："+getUser(2L).getName());
            //logger.info("__________________________睡觉结束");
        }else{
            logger.info(Thread.currentThread().getName()+"夺锁失败,断剑重铸之日，骑士归来之时");
            return;
        }
        }catch(Exception e){
       e.printStackTrace();
        }
         finally {
          //  logger.info(Thread.currentThread().getName()+": "+locktime);
            if(locktime!=null &&locktime!=0L) {
                lock.unlock("lockTest", locktime, name);
            }
        }


    }

}
